package com.yz.xyt.componet;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yz.xyt.domain.Student;
import com.yz.xyt.domain.vo.StudentImportVo;
import com.yz.xyt.service.IStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StudentListener extends AnalysisEventListener<StudentImportVo> {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudentListener.class);

    private static final Integer COUNT = 50;

    private List<StudentImportVo> studentList = new ArrayList<>();

    @Autowired
    IStudentService studentService;

    @Override
    public void invoke(StudentImportVo student, AnalysisContext analysisContext) {
        LOGGER.info("解析了一条学生记录，" + student.toString());
        studentList.add(student);

        if(studentList.size() == COUNT){
            List<Student> students = studentService.convertStudent(studentList);
            if (!students.isEmpty()){
                studentService.syncAddStudent(students);
            }
            studentList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<Student> students = studentService.convertStudent(studentList);
        if (!students.isEmpty()){
            studentService.syncAddStudent(students);
        }
        LOGGER.info("学生数据导入完成");
        studentList.clear();
    }
}
